package com.wangmeng.book.uploader;

import com.wangmeng.book.utils.JSUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.log4j.Logger;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * User: 王猛
 * Date: 13-9-23
 */
public class WeiYunUploader implements Serializable {
    public static final int COMMON_ERROR = -1;
    public static final int LOGIN_SUCCESS = 0;
    public static final int LOGIN_NO_CODE = 1;
    public static final int LOGIN＿REQ_CODE = 2;
    private static final Logger logger = Logger.getLogger(WeiYunUploader.class);
    private HttpContext context = new BasicHttpContext();
    private String uin;
    private String pwd;
    private String sKey;
    private String wqKey;
    private String checkCode;
    private Cookie uiKeyCookie;
    private Cookie ptvfsessionCookie;
    private Cookie ptispCookie;
    private Cookie confirmuinCookie;
    private CookieStore cs;
    private boolean isLogin = false;

    public WeiYunUploader(String uid, String pwd) {
        this.uin = uid;
        this.pwd = pwd;
        cs = new BasicCookieStore();
        context.setAttribute(ClientContext.COOKIE_STORE, cs);
    }

    public int getLoginType() {
        HttpGet index = new HttpGet("http://ui.ptlogin2.weiyun.com/cgi-bin/login?appid=527020901&s_url=http%3A%2F%2Fwww.weiyun.com%2Fweb%2Fcallback%2Fqq_login_ok.html&style=11&target=self&link_target=blank&hide_close_icon=1");
        HttpGet hp = new HttpGet("http://check.ptlogin2.weiyun.com/check?regmaster=&uin=" + uin + "&appid=527020901&js_ver=10049&js_type=1&login_sig=i-VJCaPZuXUc6hx59qmfyxxVF6-jV7vh64wd2a97NvTiisMHUCgP*Q7AfA1jBzMU&u1=http%3A%2F%2Fwww.weiyun.com%2Fweb%2Fcallback%2Fqq_login_ok.html");
        HttpClient client = new DefaultHttpClient();
        try {
            HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
            index.setHeader("Cookie","pgv_pvid=6333993208; pgv_info=ssid=s4057906406");
            HttpResponse indexResp = client.execute(index, context);
            if (indexResp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                indexResp.getEntity().writeTo(System.out);
                for(Cookie ck:cs.getCookies()){
                    if(ck.getName().equals("uikey")){
                        uiKeyCookie = ck;
                    }
                }
                HttpResponse hr = client.execute(hp, context);
                if (hr.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    ByteArrayOutputStream bout = new ByteArrayOutputStream();
                    hr.getEntity().writeTo(bout);
                    for(Cookie ck:cs.getCookies()){
                        if(ck.getName().equals("ptvfsession")){
                            ptvfsessionCookie = ck;
                        } else if(ck.getName().equals("ptisp")){
                            ptispCookie = ck;
                        } else if(ck.getName().equals("confirmuin")){
                            confirmuinCookie = ck;
                        }
                    }
                    String content = new String(bout.toByteArray(), "UTF-8");
                    int bIndex = content.indexOf("(");
                    int eIndex = content.lastIndexOf(")");
                    content = content.substring(bIndex + 1, eIndex);
                    String[] dataList = content.split(",");
                    if (dataList[0].equals("'0'")) {
                        checkCode = dataList[1].trim().substring(1, 5);
                        return LOGIN_NO_CODE;
                    } else {
                        return LOGIN＿REQ_CODE;
                    }
                }
            }
        } catch (IOException e) {
            logger.error("get login type error!", e);
        } finally {
            client.getConnectionManager().shutdown();
        }
        return COMMON_ERROR;
    }

    public byte[] loginImage() {
        HttpGet hp = new HttpGet("http://captcha.qq.com/getimage?&uin=" + this.uin);
        HttpClient client = new DefaultHttpClient();
        try {
            HttpResponse hr = client.execute(hp, context);
            if (hr.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                hr.getEntity().writeTo(bout);
                return bout.toByteArray();
            }
        } catch (IOException e) {
            logger.error("read login image error!", e);
        } finally {
            client.getConnectionManager().shutdown();
        }
        return null;
    }

    public int login(String code) {
        int backCode = COMMON_ERROR;
        if (checkCode != null && checkCode.length() > 0) {
            this.checkCode = code;
        }
        HttpClient client = new DefaultHttpClient();
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine se = sem.getEngineByName("js");
        try {
            se.eval(JSUtils.getScript());
            String ss = "var U = uin2hex(\"" + uin + "\");\n" +
                    "var M = \"" + pwd + "\" \n" +
                    "var I = hexchar2bin(md5(M)); \n" +
                    "var H = md5(I + U);  \n" +
                    "var V = \"" + this.checkCode + "\";\n" +
                    "var G = md5(H + V.toUpperCase());";
            se.eval(ss);
            String ePwd = se.get("G").toString();
            HttpGet hg = new HttpGet("http://ptlogin2.weiyun.com/login?u=" + uin + "&p=" + ePwd + "&verifycode=" + checkCode + "&aid=527020901&u1=http%3A%2F%2Fwww.weiyun.com%2Fweb%2Fcallback%2Fqq_login_ok.html&h=1&ptredirect=0&ptlang=2052&from_ui=1&dumy=&low_login_enable=1");
            HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
            cs.clear();
            String cStr = "pgv_pvid=6333993208; pgv_info=ssid=s4057906406; uikey="+uiKeyCookie.getValue()+"; confirmuin="+confirmuinCookie.getValue()+"; ptvfsession="+ptvfsessionCookie.getValue()+"; ptisp="+ptispCookie.getValue()+"; ptui_loginuin=52128513";
            hg.setHeader("Cookie",cStr);
            HttpResponse hr = client.execute(hg);

            if (hr.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                hr.getEntity().writeTo(bout);
                String content = new String(bout.toByteArray(), "UTF-8");
                int bIndex = content.indexOf("(");
                int eIndex = content.indexOf(")");
                content = content.substring(bIndex + 1, eIndex);
                String[] vls = content.split(",");
                if (vls[0].equals("'0'")) {
                    Header[] hds = hr.getAllHeaders();
                    int num = 0;
                    for (Header hd : hds) {
                        if (hd.getName().trim().equals("Set-Cookie")) {
                            String cv = hd.getValue();
                            String[] scv = cv.split(";");
                            if (scv.length > 0) {
                                String[] svls = scv[0].split("=");
                                if (svls.length == 2) {
                                    if (svls[0].trim().equalsIgnoreCase("skey") && (num != 1 || num != 3)) {
                                        sKey = svls[1].trim();
                                        num += 1;
                                    } else if (svls[0].trim().equalsIgnoreCase("ptwebqq") && (num != 2 || num != 3)) {
                                        wqKey = svls[1].trim();
                                        num += 2;
                                    }
                                }
                            }
                        }
                        if (num == 3) {
                            break;
                        }
                    }
                    isLogin = true;
                    return LOGIN_SUCCESS;
                }
            }
        } catch (Exception ex) {
            logger.error("login error", ex);
        } finally {
            client.getConnectionManager().shutdown();
        }
        return backCode;
    }
}
